package com.liu.netty;

import com.liu.netty.pojo.Message;
import com.liu.netty.util.DateTimeUtil;
import com.liu.netty.util.ImageUtils;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;


public class ServerHandler extends SimpleChannelInboundHandler<String> {




    protected void messageReceived(ChannelHandlerContext channelHandlerContext, String s) throws Exception {
        System.out.println("接收到的消息为："+s);
       Message message = MessageUtil.messageDecode(s);

        String msg="";

        if (message.getCommandStyle().equalsIgnoreCase("1")){
            switch (Integer.parseInt(message.getDataID())){
                case 1:// 登录信息
                    msg ="###<TaskID="+message.getTaskID()+";TaskContent{ResultFlg=0;Content<>}>###";
                    break;
                case 2://心跳
                    String time = DateTimeUtil.getTodayChar19();
                    msg ="###<TaskID=" + message.getTaskID() + ";TaskContent{ResultFlg=0;Content<DateTime=" + time + ">}>###";
                    break;
                case 3:// 上报图片信息
                    boolean flag =ImageUtils.base64DecodeImage(message.getImage(),"d:/image","d:/image/123"+ System.currentTimeMillis() +".jpg",false);
                    System.out.println("照片结果："+flag);
                    msg ="###<TaskID="+message.getTaskID()+";TaskContent{ResultFlg=0;Content<>}>###";
                    break;
                case 4:// 设备运行信息
                    msg ="###<TaskID="+message.getTaskID()+";TaskContent{ResultFlg=0;Content<>}>###";
                    break;
                case 5:// 上报错误信息
                    msg ="###<TaskID="+message.getTaskID()+";TaskContent{ResultFlg=0;Content<>}>###";
                    break;
                case 6:// 上报自检日志
                    msg ="###<TaskID="+message.getTaskID()+";TaskContent{ResultFlg=0;Content<>}>###";
                    break;
                case 7:// 上报传感器数据
                    msg ="###<TaskID="+message.getTaskID()+";TaskContent{ResultFlg=0;Content<>}>###";
                    break;

            }
        }



        System.out.println(msg);
        channelHandlerContext.writeAndFlush(msg);
    }

//    ###<TaskID=00188;TaskFlag=1;TaskContent{ObjectAddress=sx0047;CommandStyle=1;DataID=1;DataContent<Address=sx0047;SoftVersion=SV120190903;HardwareVersion=HV120190902>}>###



    /**
     * 新客户端接入
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("channelActive");
    }

    /**
     * 客户端断开
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("channelInactive");
    }

    /**
     * 异常
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
    }

}
